package com.taokatao.cardmee.business.cardcrud;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.taokatao.cardmee.ActivityCollector;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.UploadCardIconInfo;
import com.taokatao.cardmee.business.cardcode.CardCodeActivity;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.db.CardGradeDao;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.db.model.CardGrade;
import com.taokatao.cardmee.db.model.CardStore;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 填写卡号添加卡片<br/>
 * 自定义卡片可额外编辑图标和商家名称<br/>
 * 无法输入卡号的时候可以通过手机号和名称添加卡片
 */
public class CardAddByCodeActivity extends BaseActivity implements View.OnClickListener, TitleLayout.Callback, FastCompareLayout.Callback {

    @BindView(R.id.l_title) TitleLayout layTitle;
    @BindView(R.id.e_business_name) EditText eBusinessName;
    @BindView(R.id.e_value) PatternEditText eValue;
    @BindView(R.id.i_icon) ImageView iIcon;
    @BindView(R.id.i_scan_code) ImageView iScanCode;
    @BindView(R.id.t_forget_code) TextView tForgetCode;
    @BindView(R.id.i_custom) ImageView iCustom;

    @BindView(R.id.e_username) EditText eUsername;
    @BindView(R.id.e_phone) EditText ePhone;
    @BindView(R.id.t_back_to_code) TextView tBackToCode;

    @BindView(R.id.l_mode_1) View lMode1;
    @BindView(R.id.l_mode_2) View lMode2;

    private String sLocalBusinessIcon;
    private String sUploadedIconUrl;

    private SheetDialog dlgSheet;

    private int styleColor;
    private boolean isCustomMode;
    private CardStore cardStore;
    private String currInputMode = "code";

    @BindView(R.id.v_business_name_mirror) View vBusinessNameMirror;
    @BindView(R.id.l_fast_compare) FastCompareLayout lFastCompare;
    GradientColorView vGradientColor;
    @BindView(R.id.v_icon_background) GradientColorView vIconBackground;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_add_by_code);
        ButterKnife.bind(this);

        String inputContent = getIntent().getStringExtra("extra_card_code");
        if (!TextUtils.isEmpty(inputContent)) {
            eValue.setText(inputContent);
        }

        cardStore = (CardStore) getIntent().getSerializableExtra("extra_card_store");
        isCustomMode = C.settings.BUSINESS_OTHER_ID == cardStore.getBusinessId();

        cropAspectX = 1;
        cropAspectY = 1;
        expectedOutputCropWidth = 300;
        expectedOutputCropHeight = (int) (1f * expectedOutputCropWidth * cropAspectY / cropAspectX);

        layTitle.setCallback(this);
        vGradientColor = (GradientColorView) layTitle.getFitView();
        tForgetCode.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.UNDERLINE_TEXT_FLAG);
        tBackToCode.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.UNDERLINE_TEXT_FLAG);
        Utils.throttleFirstClick(iScanCode, this);
        lFastCompare.setCallback(this);
        vIconBackground.setDynamicChangeMode(GradientColorView.MODE_CLIP);

        if (isCustomMode) {
            iCustom.setVisibility(View.VISIBLE);
            eBusinessName.setEnabled(true);
            styleColor = 0xFF4C4C4C;
        } else {
            eBusinessName.setEnabled(false);
            eBusinessName.setText(cardStore.getBusinessName());
            if (!TextUtils.isEmpty(cardStore.getBusinessIcon())) {
                Glide.with(this).load(cardStore.getBusinessIcon()).centerCrop().into(iIcon);
            }
            if (!TextUtils.isEmpty(cardStore.getBackColor()) && cardStore.getBackColor().length() == 7 && cardStore.getBackColor().startsWith("#")) {
                styleColor = Color.parseColor(cardStore.getBackColor());
            } else {
                styleColor = 0xFF4C4C4C;
            }
        }

        vIconBackground.setBackgroundColor(styleColor);
        layTitle.switchContentStyleByColor(styleColor);
        Utils.fitSysWindowAndSetStatusBarMode(styleColor, vGradientColor);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final int statusBarHeight = Utils.calcStatusBarHeight(this);
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) vBusinessNameMirror.getLayoutParams();
            lp.topMargin += statusBarHeight;
        }

        RxTextView.textChanges(eBusinessName).debounce(C.settings.ANIMATION_TIME, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CharSequence>() {
                    @Override
                    public void call(CharSequence s) {
                        if (eBusinessName.isEnabled()) lFastCompare.filter(s.toString());
                    }
                });

        eBusinessName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (eBusinessName.isEnabled() && !TextUtils.isEmpty(eBusinessName.getText())) {
                    lFastCompare.filter(eBusinessName.getText().toString());
                }
            }
        });
        eBusinessName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && eBusinessName.isEnabled() && !TextUtils.isEmpty(eBusinessName.getText())) {
                    lFastCompare.filter(eBusinessName.getText().toString());
                }
            }
        });
        eValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lFastCompare.animHide();
            }
        });
        eValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    lFastCompare.animHide();
                }
            }
        });
    }

    @Override
    public void onMenuClick(TitleLayout lTitle, String flag) {
        Utils.onMobEvent(this, "clickSaveButtonOfManualInput");
        String businessName = eBusinessName.getText().toString().trim();
        if (TextUtils.isEmpty(businessName)) {
            Utils.showToast("品牌名称不能为空");
            return;
        }

        String cardNo = eValue.getTextWithoutCharSpace();
        String mUsername = eUsername.getText().toString();
        String mPhone = ePhone.getText().toString();
        if (TextUtils.equals("code", currInputMode)) {
            if (TextUtils.isEmpty(cardNo)) {
                Utils.showToast("卡号不能为空");
                return;
            }
        } else if (TextUtils.equals("nameAndTel", currInputMode)) {
            if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPhone)) {
                Utils.showToast("姓名和电话不能为空");
                return;
            }
        }

        if (!isCustomMode) {
            requestAddCard();
        } else {
            if (TextUtils.isEmpty(sLocalBusinessIcon)) {
                sLocalBusinessIcon = generateBusinessIcon(businessName);
            }
            if (sUploadedIconUrl == null) {
                requestUploadCardIcon();
            } else {
                requestAddCard();
            }
        }
    }

    @Override
    @OnClick({R.id.i_custom, R.id.t_forget_code, R.id.t_back_to_code})
    public void onClick(View v) {
        if (v == iScanCode) {
            Utils.onMobEvent(this, "clickScanOfAddCard");
            Intent intent = new Intent(this, CardCodeScanActivity.class);
            intent.putExtra("launcher_mode", "input");
            intent.putExtra("extra_name", eBusinessName.getText().toString().trim());
            startActivityForResult(intent, REQUEST_CODE_SCAN_CODE);
        } else if (v == tForgetCode) {
            String businessName = eBusinessName.getText().toString().trim();
            if (TextUtils.isEmpty(businessName)) {
                Utils.showToast("品牌名称不能为空");
                return;
            }
            lFastCompare.animHide();
            Utils.onMobEvent(this, "clickForgetCardNumberOfAddCard");
            currInputMode = "nameAndTel";
            lMode2.setVisibility(View.VISIBLE);
            lMode1.setVisibility(View.GONE);
        } else if (v == tBackToCode) {
            Utils.onMobEvent(this, "clickReturnInputCardNumberOfAddCard");
            currInputMode = "code";
            lMode2.setVisibility(View.GONE);
            lMode1.setVisibility(View.VISIBLE);
        } else if (v == iCustom) {
            showBusinessIconDialog();
        }
    }

    @Override
    public void onCardStoreSelected(View view, CardStore cs) {
        cardStore = cs;
        eBusinessName.setEnabled(false);
        eBusinessName.clearFocus();
        Utils.hideSoftInputFromWindowAlways(this);
        eBusinessName.setText(cardStore.getBusinessName());

        if (!TextUtils.isEmpty(cardStore.getBackColor()) && cardStore.getBackColor().length() == 7 && cardStore.getBackColor().startsWith("#")) {
            styleColor = Color.parseColor(cardStore.getBackColor());
        } else {
            styleColor = 0xFF4C4C4C;
        }
        vGradientColor.dynamicChangeColor(Utils.colorBurn(styleColor));
        vIconBackground.dynamicChangeColor(styleColor);
        layTitle.switchContentStyleByColor(styleColor);

        iCustom.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                iCustom.setVisibility(View.GONE);
            }
        }).start();
        if (!TextUtils.isEmpty(cardStore.getBusinessIcon())) {
            Glide.with(this).load(cardStore.getBusinessIcon()).centerCrop().into(iIcon);
        }
    }

    @Override
    protected void onHideSoftInput() {
        super.onHideSoftInput();
        lFastCompare.animHide();
    }

    private void showBusinessIconDialog() {
        if (dlgSheet == null) {
            dlgSheet = new SheetDialog.Builder(this)
                    .addMenu("拍照", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openCamera();
                        }
                    })
                    .addMenu("从相册选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openPhotos();
                        }
                    }).create();
        }
        dlgSheet.show();
    }

    private void requestUploadCardIcon() {
        ApiManager.i().uploadCardIcon(this, new File(sLocalBusinessIcon), new SubscriberAdapter<RespWrapper<UploadCardIconInfo>>() {
            @Override
            public void onNext(RespWrapper<UploadCardIconInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    sUploadedIconUrl = o.decode(UploadCardIconInfo.class).busIconUrl;
                    requestAddCard();
                }
            }
        }.showProgress(this));
    }

    private void requestAddCard() {
        CardGradeDao cardGradeDao = App.i().getCommonDBSession().getCardGradeDao();
        List<CardGrade> cardGradeList = cardGradeDao.queryBuilder().where(CardGradeDao.Properties.BusinessId.eq(cardStore.getBusinessId()))
                .orderAsc(CardGradeDao.Properties.Sort).list();

        if (cardGradeList != null && cardGradeList.size() > 0) {
            long defaultGradeId = cardGradeList.get(0).getId();

            long uuid = App.i().getCurrUser().getUuid();
            final String mCardNo = eValue.getTextWithoutCharSpace();
            final String cardUser = eUsername.getText().toString().trim();
            final String cardTel = ePhone.getText().toString().trim();
            final String customBusiness = isCustomMode ? eBusinessName.getText().toString().trim() : "";
            final String customPic = isCustomMode ? sUploadedIconUrl : "";
            ApiManager.i().addCard(this, uuid, mCardNo, "", "", cardStore.getBusinessId(), defaultGradeId, "", "", "",
                    customBusiness, customPic, cardUser, cardTel, new SubscriberAdapter<RespWrapper<Card>>() {
                        @Override
                        public void onNext(RespWrapper<Card> o) {
                            super.onNext(o);
                            if (o.code == C.http.RESULT_CODE_SUCCESS) {
                                Intent intent = new Intent(CardAddByCodeActivity.this, CardCodeActivity.class);

                                Card card = o.decode(Card.class);
                                card.setMCardNo(mCardNo);
                                card.setMCardIcon(cardStore.getBusinessIcon());
                                card.setBackColor(Utils.formatColor(styleColor));
                                card.setBusinessName(cardStore.getBusinessName());
                                card.setBusinessId(cardStore.getBusinessId());
                                card.setIsMyCard(Card.STATUS_MY_CARD);
                                card.setAnotherBusiness(customBusiness);
                                card.setBuPic(customPic);
                                card.setCardUser(cardUser);
                                card.setCardTel(cardTel);
                                card.setBarcodeFormat(cardStore.getBarcodeFormat());
                                card.setBarcodeStatus(cardStore.getBarcodeStatus());
                                intent.putExtra("extra_card", card);
                                startActivity(intent);

                                Utils.postMainThreadBusEvent(BusEvent.CARD_ADD, card);

                                ActivityCollector.finishActivity(CardSearchActivity.class);
                                ActivityCollector.finishActivity(CardAddByCodeActivity.class);
                            }
                        }
                    }.showProgress(this));

        } else {
            Utils.showToast("该商家类型数据[卡片等级]缺失，暂时无法添加");
        }
    }

    @Override
    protected void onPictureQueryOut(String path) {
        super.onPictureQueryOut(path);
        if (!TextUtils.isEmpty(path)) {
            Glide.with(this).load(new File(sLocalBusinessIcon = path))
                    .centerCrop().bitmapTransform(App.i().getCropCircleTransformation())
                    .into(iIcon);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_SCAN_CODE) {
            if (resultCode == RESULT_OK) {
                String content = data.getStringExtra("extra_content");
                String format = data.getStringExtra("extra_format");
                Utils.logd(getClass().getSimpleName() + " scan content [type:" + format + "] is : " + content);
                Utils.onMobEvent(this, "scanBarcode");
                eValue.setText(content);
            }
        }
    }

    /**
     * 自定义商家未设置icon时候，自动根据商家名称生成icon
     *
     * @param businessName 商家名称
     * @return 图片临时保存的路径
     */
    private String generateBusinessIcon(@NonNull String businessName) {
        Bitmap bmpIcon = makeLetterIcon(businessName);
        File fIconPicture = new File(getExternalCacheDir(), "pic_business_icon_" + System.currentTimeMillis() + ".jpg");
        String savePath = fIconPicture.getAbsolutePath();
        Utils.saveImage(bmpIcon, savePath);
        return savePath;
    }

    private Bitmap makeLetterIcon(@NonNull String name) {
        String s = name.substring(0, 1);
        int size = 300; // px
        Bitmap result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(0xFFD2D2D2);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        paint.setColor(0xFF434343);
        paint.setFakeBoldText(true);
        final float SCALE = getResources().getDisplayMetrics().density;
        float dips = 350 / SCALE;
        paint.setTextSize(dips);
        float[] textWidths = new float[1];
        paint.getTextWidths(s, textWidths);
        canvas.drawText(s, (size - textWidths[0]) / 2, size / 2 + dips * 0.4f, paint);
        return result;
    }
}
